import LogService from "../service/LogService";

export class BuffUtils {

  static map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

  static decode(input){
    let o = [];
    let c1, c2, c3;
    let e1, e2, e3, e4;
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
    for(var i = 0; i < input.length;) {
      e1 = BuffUtils.map.indexOf(input.charAt(i++));
      e2 = BuffUtils.map.indexOf(input.charAt(i++));
      e3 = BuffUtils.map.indexOf(input.charAt(i++));
      e4 = BuffUtils.map.indexOf(input.charAt(i++));
      c1 = e1 << 2 | e2 >> 4;
      c2 = (e2 & 15) << 4 | e3 >> 2;
      c3 = (e3 & 3) << 6 | e4;
      o.push(c1);
      if (e3 != 64) { o.push(c2); }
      if (e4 != 64) { o.push(c3); }
    }
    return o;
  }

  /**
   * 数组转换为 buff
   * @param arr
   * @returns {ArrayBufferLike}
   */
  static arrToBuffer(arr){
    const typedArray = new Uint8Array(arr);
    return typedArray.buffer;
  }

  static buffToArr(buff){
    let data = new Uint8Array(buff);
    let arr = [];
    data.forEach(value => arr.push(value));
    return arr;
  }

  static getArr(src, start, len) {
    let arrs = [];
    let i, j;
    for (i = start, j = 0; j < len; ++i, ++j) {
      arrs[j] = src[i];
    }
    return arrs;
  }

  static to16(arr){
    let temp = arr.map(value => {
      value = Number(value);
      return value.toString(16);
    })

    return temp;
  }

  static intToBigBytes(numb, len) {
    if (numb < 0){
      numb = 0xffffffff + numb +1;
    }
    let arr = [];
    for (let i = 0; i < len; i++) {
      arr[len-i-1] = (numb % 256) & 0xff;
      numb /= 256;
    }
    return arr;
  }

  // 大端
  static BigBytesToInt(src, len) {
    let value = 0;

    for (let i = len - 1; i >= 0; --i) {
      value |= (src[i] & 0xFF) << ((len - 1 - i) * 8);
    }
    return value;
  }

}

export class Queue {
  list = [];
  size = 0;

  constructor(size) {
    this.size = size;
  }

  clear = () =>{
    this.list = [];
  }

  addArr = (arr) => {

    arr.forEach(v =>{
      this.add(v);
    })
    return true;
  }

  add = (data) => {
    if (data == null) {
      return false;
    }
    //如果传递了size参数就设置了队列的大小
    if (this.list.length == this.size) {
      this.pop();
      LogService.error("push err list is full");
    }
    this.list.unshift(data);
    return true;
  }

  getData = ()=>{
    return this.list.pop();
  }

  getArr = (len)=>{
    let arr = [];
    for (let i = 0; i < len; i++) {
      arr.push(this.list.pop())
    }
    return arr;
  }


  getSize = ()=>{
    return this.list.length;
  }
}
